package com.krtech.wecard.module.ramble.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.krtech.wecard.framework.utils.LoginUtil;
import com.krtech.wecard.module.sys.entity.SysUser;
import com.krtech.wecard.utils.DfsUtil;
import com.krtech.wecard.utils.WxUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.krtech.wecard.module.ramble.entity.RambleShareQrcode;
import com.krtech.wecard.module.ramble.mapper.RambleShareQrcodeMapper;
import com.krtech.wecard.module.ramble.service.RambleShareQrcodeService;

@Service
public class RambleShareQrcodeServiceImpl extends ServiceImpl<RambleShareQrcodeMapper, RambleShareQrcode> implements RambleShareQrcodeService {

    @Autowired
    private WxUtil wxUtil;

    private static String URL = "https://seemax.cc";

    @Override
    public String getQrCode() {
        SysUser userInfo = LoginUtil.getUserInfo();

        //如果当前已经有了就不用生成了
        RambleShareQrcode shareQrcode = this.getOne(new QueryWrapper<RambleShareQrcode>().eq(RambleShareQrcode.COL_PHONE, userInfo.getPhone()));
        if (shareQrcode != null) {
            return shareQrcode.getQrcodeUrl();
        }

        String accessToken = wxUtil.getAccessToken();

        HttpRequest post = HttpUtil.createPost("https://api.weixin.qq.com/wxa/getwxacode?access_token=" + accessToken);

        String code = IdUtil.simpleUUID();

        HashMap<Object, Object> map = new HashMap<>();
        map.put("path", "/pages/index/index?code=" + code);

        post.body(JSONUtil.toJsonStr(map));
        HttpResponse execute = post.execute();

        File file = FileUtil.writeBytes(execute.bodyBytes(), "/tmp/generateQrCode/" + code + ".jpg");

        DfsUtil dfsUtil = new DfsUtil();
        DfsUtil.DfsFile upload = dfsUtil.upload(file);

        //将地址保存下来
        String url = URL + upload.getSrc();

        //保存一份
        RambleShareQrcode saveQrCode = new RambleShareQrcode();
        saveQrCode.setCreatedTime(new Date());
        saveQrCode.setCode(code);
        saveQrCode.setNickName(userInfo.getNickName());
        saveQrCode.setOpenId(userInfo.getMipOpenId());
        saveQrCode.setPhone(userInfo.getPhone());
        saveQrCode.setQrcodeUrl(url);
        this.save(saveQrCode);

        return url;
    }
}





